package json;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import json.Node;
public class Recursion {

Recursion(){}
	

	StringBuffer returnStr=new StringBuffer();
	public void recursionFn(List list, Node node){
		if(hasChild(list,node)){
			returnStr.append("{"+"\""+"id"+"\""+":");
			returnStr.append(node.getId());
			returnStr.append(","+"\""+"parentId"+"\""+":");
			returnStr.append(node.getParentId());
			returnStr.append(","+"\""+"children"+"\""+":[");
			List childList = getChildList(list,node);
			Iterator it = childList.iterator();
			while(it.hasNext()){
				Node n = (Node)it.next();
				recursionFn(list,n);
			}
			returnStr.append("]},");
		}else{
			returnStr.append("{"+"\""+"id"+"\""+":");
			returnStr.append(node.getId());
			returnStr.append(","+"\""+"parentId"+"\""+":");
			returnStr.append(node.getParentId());
			returnStr.append(","+"\""+"leaf"+"\""+":"+"\""+"true"+"\""+"},");
			}
		}
	public boolean hasChild(List list, Node node){
		return (getChildList(list,node).size()) > 0 ?true:false;
	}
	public List getChildList(List list, Node node){
		List li = new ArrayList();
		Iterator it = list.iterator();
		while(it.hasNext()){
			Node n = (Node)it.next();
			if(n.getParentId()==node.getId()){
				li.add(n);
				}
		}return li;
	}
	public String modifyStr(String returnStr){
		return ("["+returnStr+"]").replaceAll(",]", "]");
	}
	/*public static void main(String[] args){
		Recursion r = new Recursion();
		r.recursionFn(r.nodeList, new Node(1,0));
		System.out.println(r.modifyStr(r.returnStr.toString()));
	}*/
	

}
